﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

public class JwtAuthorizationFilter : IAuthorizationFilter
{
    private readonly string _secretKey;

    public JwtAuthorizationFilter(string secretKey)
    {
        _secretKey = secretKey;
    }

    public void OnAuthorization(AuthorizationFilterContext context)
    {
        if (context.ActionDescriptor.EndpointMetadata.Any(m => m is AllowAnonymousAttribute))
        {
            return; // 直接跳过验证
        }

        var token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();

        if (string.IsNullOrEmpty(token))
        {
            context.Result = new UnauthorizedResult();
            return;
        }

        try
        {
            var tokenHandler = new JwtSecurityTokenHandler();
            var key = Encoding.ASCII.GetBytes(_secretKey);
            tokenHandler.ValidateToken(token, new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(key),
                ValidateIssuer = false,
                ValidateAudience = false,
                ClockSkew = TimeSpan.Zero
            }, out SecurityToken validatedToken);

            var jwtToken = (JwtSecurityToken)validatedToken;
            var claims = jwtToken.Claims;
            context.HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity(claims));
            // 将用户信息存储在 HttpContext.Items 中
            var displayName = claims.FirstOrDefault(c => c.Type == "displayName")?.Value;
            var guid = claims.FirstOrDefault(c => c.Type == "guid")?.Value;
            context.HttpContext.Items["DisplayName"] = displayName;
            context.HttpContext.Items["Guid"] = guid;
            context.HttpContext.Items["IP"] = context.HttpContext.Connection.RemoteIpAddress?.ToString() ?? "未知";
        }
        catch
        {
            context.Result = new UnauthorizedResult();
        }
    }
}